package com.wxxymaker.edu.service;

import com.blade.ioc.annotation.Bean;
import com.wxxymaker.edu.model.entity.Course;
import com.wxxymaker.edu.model.entity.CourseSpecialty;
import com.wxxymaker.edu.model.entity.CourseSubject;
import com.wxxymaker.edu.model.entity.User;
import com.wxxymaker.edu.utils.TimeUtils;
import io.github.biezhi.anima.Anima;
import io.github.biezhi.anima.core.AnimaQuery;
import io.github.biezhi.anima.core.Joins;
import io.github.biezhi.anima.enums.OrderBy;
import io.github.biezhi.anima.page.Page;
import lombok.extern.slf4j.Slf4j;

/**
 * @AUTHOR soft
 * @DATE 2018/9/6 18:10
 * @DESCRIBE 课程操作业务层
 */
@Bean
@Slf4j
public class CourseService implements Service<Course> {

    public long count(Integer userId) {
        Course course = new Course();
        course.setUserId(userId);
        return count(course);
    }
    /**
     * 课程数查询
     * @param course 条件 发布者 课程状态 所属学科
     */
    public long count(Course course) {
        AnimaQuery<Course> from = Anima.select().from(Course.class);
        if (course != null) {
            if (course.getUserId() != null) {
                from.where(Course::getUserId, course.getUserId());
            }
            if (course.getStatus() != null) {
                from.where(Course::getStatus, course.getStatus());
            }
            if (course.getSpecialtyId() != null) {
                from.where(Course::getSpecialtyId, course.getSpecialtyId());
            }
        }
        return from.count();
    }


    /**
     * 是不是有该课程id
     * @param kid 课程id
     */
    public boolean has(int kid) {
        return Anima.select().from(Course.class)
                .where(Course::getId, kid)
                .count() > 0;
    }

    /**
     * subjectId是不是包含有course
     * @param subjectId 课程id
     */
    public boolean have(int subjectId) {
        return Anima.select().from(Course.class)
                .where(Course::getSubjectId, subjectId)
                .count() > 0;
    }

    /**
     * 判断课程是否发布
     * @param kid 课程id
     */
    public boolean isPublish(int kid) {
        return Anima.select().from(Course.class)
                .where(Course::getId, kid)
                .where(Course::getStatus, 1)
                .count() > 0;
    }

    @Override
    public Course add(Course course) {
        course.setTime(TimeUtils.getTime());
        boolean rollback = Anima.atomic(() -> {
            Integer asInt = course.save().asInt();
            course.setId(asInt);
        }).catchException(e -> {
            log.error("添加失败！{}", e.getMessage());
        }).isRollback();
        return rollback ? null : course;
    }

    @Override
    public Course delete(Object pk) {
        Course course = byId(pk);
        boolean rollback = Anima.atomic(course::delete).catchException(e -> {
            log.error("删除失败！{}", e.getMessage());
        }).isRollback();
        return rollback ? null : course;
    }

    @Override
    public boolean change(Course course) {
        boolean rollback = Anima.atomic(() -> {
            course.updateById(course.getId());
        }).catchException(e -> {
            log.error("修改失败！{}", e.getMessage());
        }).isRollback();
        return !rollback;
    }

    /**
     * 获取一个课程
     * @param pk 课程id
     * @param isPublish 是否发布
     */
    public Course findOne(Integer pk, Boolean isPublish) {
        AnimaQuery<Course> join = Anima.select().from(Course.class)
                .join(Joins.with(User.class)
                        .as(Course::getUser)
                        .on(Course::getUserId, User::getId));
        if (isPublish != null) {
            join.where(Course::getStatus, isPublish?1:0);
        }
        Course course = join.byId(pk);
        if (course != null) {
            if (course.getSpecialtyId() != 0) {
                course.setSpecialty(Anima.select().from(CourseSpecialty.class).byId(course.getSpecialtyId()));
            }
            if (course.getSubjectId() != 0) {
                course.setSubject(Anima.select().from(CourseSubject.class).byId(course.getSubjectId()));
            }
        }
        return course;
    }

    @Override
    public Course byId(Object pk) {
        Course course = Anima.select().from(Course.class)
                .join(Joins.with(User.class)
                        .as(Course::getUser)
                        .on(Course::getUserId, User::getId))
                .byId(pk);
        if (course.getSpecialtyId() != 0) {
            course.setSpecialty(Anima.select().from(CourseSpecialty.class).byId(course.getSpecialtyId()));
        }
        if (course.getSubjectId() != 0) {
            course.setSubject(Anima.select().from(CourseSubject.class).byId(course.getSubjectId()));
        }
        return course;
    }

    /**
     * 获取全部类型课程 不分新热
     * @param spec 专业
     * @param sub  学科
     * @param uid  教师
     * @param page 页码
     * @param size 分页尺寸
     * @param status 课程状态 为null时 任何状态
     */
    public Page<Course> page(int spec,
                             int sub, int uid,
                             int page, int size, Integer status) {
        return this.page("all", spec, sub, uid, page, size, status);
    }
    /**
     * 分页条件查询
     * 不为0则需要满足条件
     * @param type 课程类型 新 热 全部
     * @param spec 专业
     * @param sub  学科
     * @param uid  教师
     * @param page 页码
     * @param size 分页尺寸
     * @param status 课程状态 为null时 任何状态
     */
    public Page<Course> page(String type, int spec,
                             int sub, int uid,
                             int page, int size, Integer status) {
        AnimaQuery<Course> from = Anima.select().from(Course.class);
        if (spec > 0) {
            from.where(Course::getSpecialtyId, spec);
        }
        if (sub > 0) {
            from.where(Course::getSubjectId, sub);
        }
        if (uid > 0) {
            from.where(Course::getUserId, uid);
        }
        if (status != null) {
            from.where(Course::getStatus, status);
        }
        switch (type) {
            case "hot":
                from.order(Course::getStudents, OrderBy.DESC); break;
            case "new":
                from.order(Course::getTime, OrderBy.DESC); break;
            case "all":
                from.order(Course::getId, OrderBy.DESC); break;
        }
        return from.page(page, size);
    }

    /**
     * 搜索
     * @param q 标题关键字
     * @param page 页码
     * @param size 分页尺寸
     */
    public Page<Course> search(String q, int page, int size) {
        return Anima.select().from(Course.class)
                .like(Course::getName, "%" + q + "%")
                .where(Course::getStatus, 1)
                .order(Course::getStudents, OrderBy.DESC)
                .page(page, size);
    }

    /**
     * 判断该课程是不是我发布的
     * @param uid 用户（老师）id
     * @param kid 课程id
     * @return 是否
     */
    public boolean isMyPublish(int kid, int uid) {
        return Anima.select().from(Course.class)
                .where(Course::getUserId, uid)
                .where(Course::getId, kid)
                .count() > 0;
    }

    public boolean addViews(int kid) {
        return Anima.execute("UPDATE course SET views = views+1 WHERE id = ?", kid)>0;
    }

    public boolean addStudents(int kid) {
        return Anima.execute("UPDATE course SET students = students+1 WHERE id = ?", kid)>0;
    }

    public boolean reduceStudents(int kid) {
        return Anima.execute("UPDATE course SET students = students-1 WHERE id = ?", kid)>0;
    }
}
